// pages/user_end/order/order.js
const app = getApp();
const request = require('../../../utils/request.js');
const url = require('../../../utils/url.js');
const cookie = require('../../../utils/cookie.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    bg: '#08B266',
    list1: [{
      name: '全部',
      dot: false,
      number: 0,
      checkinfo: 0
    }, {
      name: '待确认',
      dot: true,
      number: 0,
      checkinfo: 1
    }, {
      name: '待服务',
      dot: true,
      number: 0,
      checkinfo: 2
    },  {
      name: '服务中',
      dot: true,
      number: 0,
      checkinfo: 3
    }, {
      name: '等待验收',
      dot: true,
      number: 0,
      checkinfo: 7
    }, {
      name: '已完成',
      dot: false,
      number: 0,
      checkinfo: 4
    }, {
      name: '取消/退款',
      dot: false,
      number: 0,
      checkinfo: 5
    }],
    nindex: 0,
    keyword:'',
    navindex:0,
    nsindex:0,
    page: 1,
    list: [],
    checkinfo: 0,
    show: false,
    show1: false,
    datelist: [],
    timelist: [],
    active: '',
    reserveDate: "",
    isReserve:0,
    orderId: 0,
    cnum:0,
    noOrder:0,
    login:0
  },
  close1(){
    this.setData({
      show1:false
    })
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
     console.log(typeof(options.checkinfo))
     var that = this;
     if(typeof(options.checkinfo)=='string'){
       if(options.checkinfo=='0'){
          that.setData({
            navindex : 0,
            checkinfo: options.checkinfo,
            page :1,
          })
       }else{
         var navindex = parseInt(options.checkinfo)-1;
         that.setData({
          navindex :  options.checkinfo,
          checkinfo: options.checkinfo,
          page :1,
        })
       }
     }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    cookie.getCookie('userInfo', function (res) {
      if (res) {
        var etime = Date.parse(new Date()) / 1000;
        
        if (etime < res.expiretime) {
          that.setData({
            login: 1,
            token:res.token
          })
          that.getDatelist();
          that.getOrdernum();
          that.getOrder();
        }
      }else{
        that.setData({
          noOrder:1
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  reorder(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../payorder/payorder?id=' + id
    })
  },
  checkIssue(e) {
    var id = e.currentTarget.dataset.id;
	console.log(id)
	 wx.redirectTo({
	   url: '../../order/issue/issue?id=' + id,
	 })
  },
  goComment(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../leave_comment/leave_comment?id=' + id
    })
  },
  goException(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../exception/exception?id=' + id
    })
  },
  gorefund(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../refund/refund?id=' + id
    })
  },
  getDatelist:function(){
    var that = this;
    let param = {
      scoure: 'wxapp',
      token:that.data.token
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.getdatelist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if(res.data.code==1){
         that.setData({
            datelist : res.data.data,
            reserveDate : res.data.data[0].date
         })
       }
    })  	
  },
  getTimelist:function(){
    var that = this;
    let param = {
      scoure: 'wxapp',
      token:that.data.token,
      order_id: that.data.orderId,
      date: that.data.reserveDate,
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.getordertimelist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if(res.data.code==1){
         that.setData({
            timelist : res.data.data.timelist,
            show1 : true,
            service_multiple : res.data.data.multiple
         })
       }
    })  	
  },
  showTime(e){
    var that = this;
    var id = e.currentTarget.dataset.id;
    that.setData({
      orderId:id
    })
    let param = {
      scoure: 'wxapp',
      token:that.data.token,
      order_id: that.data.orderId,
      date: that.data.reserveDate,
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.getordertimelist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if(res.data.code==1){
         that.setData({
            timelist : res.data.data.timelist,
            show1 : true,
            service_multiple : res.data.data.multiple
         })
       }
    })  	
  },
  choseReserve(e) {
    var time = e.currentTarget.dataset.timestamp;
    var check = e.currentTarget.dataset.checked;
    if (check == 0) {
        wx.showToast({
          title: '当前时间不可选',
          icon: 'none'
        });
        return false;
      }
      //遍历可选时间
      var that = this;
      var  showtips = 0;
      //判断单选方式
      if(that.data.service_multiple==false){
        that.data.timelist.forEach((item,index) => { 
          var sItem = "timelist[" + index + "].active";
           if(item.timestamp==time){
            that.setData({
              [sItem]: 1,
            });                        
           }else{
            that.setData({
              [sItem]: 0,
            }); 
           }		
        })					
      }else{
        var count = 0;
        var length = that.timelist.length - 1;
        var  arrIds = [];
        that.data.timelist.forEach((item,index) => {
           if(item.active==1){
             count++;
             arrIds.push(index);
          }
        });				
        
        that.data.timelist.forEach((item,index) => {
           if(item.timestamp==time){
               if(item.active==1){
                var active = 0;
                 //判断连续性
                 if(count>0){
                   if(index==arrIds[0]){
                       var active = 0;
                     
                   }else if(index==arrIds[count-1]){
                       var active = 0;
                                            
                   }else{
                      var active = 1;
                    showtips = 2; 										   
                   }
                 }								   
                 
              }else{
                 var active = 1;
                 //判断连续性
                 if(count>0){
                   if(index==0){
                       if(that.data.timelist[index+1].active==1){
                       var active = 1;
                     }else{
                       showtips = 1;
                       var active = 0;
                     }
                   }else if(index==length){
                       if(that.data.timelist[index-1].active==1){
                       var active = 1;
                     }else{
                       showtips = 1;
                       var active = 0;
                     }										   
                   }else{
                       if(that.data.timelist[index+1].active==1||that.data.timelist[index-1].active==1){
                       var active = 1;
                     }else{
                       showtips = 1;
                       var active = 0;
                     }											   
                   }
                 }
                 
              }
              var sItem = "timelist[" + index + "].active";	
              that.setData({
                 [sItem]:active
              })										 
           }	
          })					
      }
      if(showtips==1){
        wx.showToast({
          title: '请先选择连续的时间!',
          icon: "none"
        })					
      }
      if(showtips==2){
        wx.showToast({
          title: '请先选择取消开始时间!',
          icon: "none"
        })					
      }
      //选择结果
      var chose = 0;
      var arrayIds =[];
      that.data.timelist.forEach((item,index) => {
         if(item.active==1){
           chose++;
           arrayIds.push(index);
        }
      });	
      that.setData({
        cnum:chose
      })
      if(chose==0){
        that.setData({
          isReserve:0,
          reserveShow:'',
          reserveTime:''
        })
      }else{
        that.setData({
          isReserve:1,
          reserveShow: that.data.reserveDate + ' ' + that.data.timelist[arrayIds[0]].start_time,
          reserveTime:that.data.timelist[arrayIds[0]].timestamp
        })
      }
    },
    chooseNav(e) {
      this.setData({
        navindex : e.currentTarget.dataset.current,
        checkinfo: e.currentTarget.dataset.checkinfo,
        page :1,
      })
      if(this.data.login==1){
         this.getOrder();
      }
    },
    chooseDateNav(e) {
      this.setData({
        nindex:e.currentTarget.dataset.current,
        reserveDate:e.currentTarget.dataset.date,
        isReserve:0,
        reserveShow:"",
        reserveTime:""
      })
      this.getTimelist();
    },
    doSearch(){
      this.setData({
        page:1
      })
      this.getOrdernum();
      this.getOrder();			
    },
    getOrdernum:function(){
      var that = this;
      let param = {
        scoure: 'wxapp',
        token:that.data.token,
        keyword:that.data.keyword
      }
      wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
      request.request(url.getordernum, param, url.REQUEST_METHOD_GET).then((res) => {
        wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
        if(res.data.code==1){
          var sitem = 'list1[0].number';
           that.setData({
              [sitem] :res.data.data.checkinfo
           })
           var sitem = 'list1[1].number';
           that.setData({
              [sitem] :res.data.data.checkinfo1
           })
           var sitem = 'list1[2].number';
           that.setData({
              [sitem] :res.data.data.checkinfo2
           })
           var sitem = 'list1[3].number';
           that.setData({
              [sitem] :res.data.data.checkinfo3
           })
           var sitem = 'list1[4].number';
           that.setData({
              [sitem] :res.data.data.checkinfo7
           })
           var sitem = 'list1[5].number';
           that.setData({
              [sitem] :res.data.data.checkinfo4
           })
           var sitem = 'list1[6].number';
           that.setData({
              [sitem] :res.data.data.checkinfo5
           })
         }
      })  	
    },
    getOrder: function() {
      var that = this;
      let param = {
          keyword:that.data.keyword,
					checkinfo: that.data.checkinfo,
          page:that.data.page,
          token:that.data.token
      }
      wx.showNavigationBarLoading();  //在当前页面显示导航条加载动画
      request.request(url.getorderlist, param, url.REQUEST_METHOD_GET).then((res) => {
            wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
            if (that.data.page == 1) {
                that.setData({
                  list:[],
                  noOrder:1,
                })
            }
            var contentlistTem = that.data.list;
              if (res.data.data.data.length > 0) {
                var contentlist = res.data.data.data;
                if (contentlist.length < 10) {
                  that.setData({
                    list: contentlistTem.concat(contentlist),
                    hasMoreData: false,
                    noOrder:0,
                  })
                } else {
                  that.setData({
                    list: contentlistTem.concat(contentlist),
                    hasMoreData: true,
                    page: that.data.page + 1,
                    noOrder:0,
                  })
                }
              }else{
                 that.setData({
                  hasMoreData: false
                 })
              }
      })
  
    },
    goDetail(e) {
      var id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '../order_choose/order_choose?id=' + id
      })
    },
    updateTime(){
      var that = this;
      if(!that.data.isReserve){
         wx.showToast({
          title:"请选择时间!",
          icon:"loading"
        })
        return false;
      }
      let param = {
        scoure: 'wxapp',
        token:that.data.token,
        service_start_time:that.data.reserveTime,
        service_num:that.data.cnum,
        id: that.data.orderId,
      }
      wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
      request.request(url.changeordertime, param, url.REQUEST_METHOD_GET).then((res) => {
        wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
        wx.showToast({
          title: res.data.msg,
          icon:"none"
        })
        that.setData({
          show1:false
        })
        if(res.data.code==1){
           that.setData({
						  page : 1,
					    reserveTime : '',
						  isReserve : 0,
						  cnum : 0
           })
           that.getOrder();
         }
      })  	
    },		
	acceptorder(e){
		var id = e.currentTarget.dataset.id;
		var that = this;
		let param = {
		  scoure: 'wxapp',
		  token:that.data.token,
		  id:id
		}
		wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
		request.request(url.acceptorder, param, url.REQUEST_METHOD_GET).then((res) => {
		  wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
		  wx.showToast({
		    title: res.data.msg,
		    icon:"none"
		  })
		  if(res.data.code==1){
		     that.setData({
		        page:1,
		     })
		      that.getOrdernum();
		     that.getOrder();
		   }
		})  	
	},
    cancelOrder(e) {
      var id = e.currentTarget.dataset.id;
      var that = this;
      let param = {
        scoure: 'wxapp',
        token:that.data.token,
        id:id
      }
      wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
      request.request(url.cancelorder, param, url.REQUEST_METHOD_GET).then((res) => {
        wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
        wx.showToast({
          title: res.data.msg,
          icon:"none"
        })
        if(res.data.code==1){
           that.setData({
              page:1,
           })
            that.getOrdernum();
           that.getOrder();
         }
      })  	
    },
    finishOrder(e){
      var id = e.currentTarget.dataset.id;
      var that = this;
      let param = {
        scoure: 'wxapp',
        token:that.data.token,
        id:id
      }
      wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
      request.request(url.finishorder, param, url.REQUEST_METHOD_GET).then((res) => {
        wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
        wx.showToast({
          title: res.data.msg,
          icon:"none"
        })
        if(res.data.code==1){
           that.setData({
              page:1,
           })
            that.getOrdernum();
           that.getOrder();
         }
      })  	
    },
    cancelrefund(e){
      var id = e.currentTarget.dataset.id;
      var that = this;
      let param = {
        scoure: 'wxapp',
        token:that.data.token,
        id:id
      }
      wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
      request.request(url.cancelrefund, param, url.REQUEST_METHOD_GET).then((res) => {
        wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
        wx.showToast({
          title: res.data.msg,
          icon:"none"
        })
        if(res.data.code==1){
           that.setData({
              page:1,
           })
            that.getOrdernum();
           that.getOrder();
         }
      })  	
    },
    payOrder(e){
      var id = e.currentTarget.dataset.id;
      var that = this;
      wx.requestSubscribeMessage({
        tmplIds: [
          'WCOeBpOwto_yU4ZM-hUmQePvbfY_lxKyaFK5Yi7nzao',
        ],
        success: (res) => {
          that.confirmPayOrder(id);
        },
        fail: (res) => {
          that.confirmPayOrder(id);
        },
      })
    },
    confirmPayOrder(id){
      var that = this;
      let param = {
        scoure: 'wxapp',
        token:that.data.token,
        id:id
      }
      wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
      request.request(url.payorder, param, url.REQUEST_METHOD_GET).then((res) => {
        wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
        if(res.data.code==1){
            //直接支付成功
            //跳转订单详情页
           let orderId = res.data.data.id;
           if(res.data.data.pay_money>0){
             var config = JSON.parse(res.data.data.wxconfig);
             console.log("成功", JSON.parse(res.data.data.wxconfig));
             wx.requestPayment({
               'timeStamp': config.timestamp,
               'nonceStr':config.nonceStr,
               'package': config.package,
               'signType': config.signType,
               'paySign': config.paySign,
               'success': function(res2) {
                 console.log("成功", res2)
                 if (res2.errMsg == 'requestPayment:ok') {
                    wx.navigateTo({
                        url: '../order_choose/order_choose?id='+orderId,
                      })
                      return false;
                 } 
               },
               'fail': function(res2) {
                 console.log("失败", res2)
                 wx.navigateTo({
                  url: '../order_choose/order_choose?id='+orderId,
                 })
                 return false;
               },
               'complete': function(res2) {}
             })
           }else{
             wx.showToast({
               title: '支付成功',
               icon:'none'
             })
             wx.redirectTo({
               url: '../order_choose/order_choose?id='+orderId,
              })
              return false;      
           }
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none',
            duration:2000
          })
        }
      })  	      
    },
    payconfig(e){
      var id = e.currentTarget.dataset.id;
      var that = this;
      let param = {
        scoure: 'wxapp',
        token:that.data.token,
        id:id
      }
      wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
      request.request(url.payconfig, param, url.REQUEST_METHOD_GET).then((res) => {
        wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
        if(res.data.code==1){
            //直接支付成功
            //跳转订单详情页
           let orderId = res.data.data.id;
           if(res.data.data.pay_money>0){
             var config = JSON.parse(res.data.data.wxconfig);
             console.log("成功", JSON.parse(res.data.data.wxconfig));
             wx.requestPayment({
               'timeStamp': config.timestamp,
               'nonceStr':config.nonceStr,
               'package': config.package,
               'signType': config.signType,
               'paySign': config.paySign,
               'success': function(res2) {
                 console.log("成功", res2)
                 if (res2.errMsg == 'requestPayment:ok') {
                      wx.redirectTo({
                        url: '../order_choose/order_choose?id='+orderId,
                      })
                      return false;
                 } 
               },
               'fail': function(res2) {
                 console.log("失败", res2)
                 wx.redirectTo({
                  url: '../order_choose/order_choose?id='+orderId,
                 })
                 return false;
               },
               'complete': function(res2) {}
             })
           }else{
             wx.showToast({
               title: '支付成功',
               icon:'none'
             })
             wx.redirectTo({
               url: '../order_choose/order_choose?id='+orderId,
              })
              return false;      
           }
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none',
            duration:2000
          })
        }
      })  	      
    },
    changekey(e){
      var keyword =e.detail.value;
      this.setData({
        keyword:keyword
      })
    }


})